import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui';

import 'package:bluetooth_print/bluetooth_print.dart';
import 'package:bluetooth_print/bluetooth_print_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

import 'package:flutter_admin/pages/common/cry/cry_button.dart';

import 'package:qr_flutter/qr_flutter.dart';
import '../../../../generated/l10n.dart';

class BluetoothView extends StatelessWidget {

  final List<Map<String,dynamic>> configList;

  final Map<String,dynamic> data;

  final String qrCode;

  final String? title;

  BluetoothView({Key? key,required this.configList,required this.data,required this.qrCode,this.title}): super(key: key);

  final GlobalKey rootWidgetKey = GlobalKey();

  @override
  Widget build(BuildContext context) {

    // 将widget转成图片
    _capturePng() async {
      try {
        RenderRepaintBoundary? boundary = rootWidgetKey.currentContext!
            .findRenderObject() as RenderRepaintBoundary?;
        var image = await boundary!.toImage(pixelRatio: 6.0);
        //截图
        ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
        var pngBytes = byteData!.buffer.asUint8List();
        String base64Image = base64Encode(pngBytes);
        showDialog(
          context: context,
          builder: (BuildContext context) => Dialog(
            child: BluetoothDeviceDialog(
                data: base64Image, image: pngBytes),
          ),
        ).then((v) {});
      } catch (e) {
        print(e);
      }
      return null;
    }

    Widget _textRow(Map<String, dynamic> config){
      TextStyle textStyle = TextStyle(fontSize: 20,fontWeight: FontWeight.bold,);
      return Container(
        padding: EdgeInsets.only(top: 2),
        child: Row(
          children: [
            Text(config['label']+"：",style: textStyle,),
            Expanded(child: Text(data[config['key']],style: textStyle,)),
            SizedBox(width: 10,),
          ],
        ),
      );
    }

    // TODO: implement build
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: '打印',
          onPressed: () async {
            _capturePng();
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text("打印预览"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            RepaintBoundary(
              key: rootWidgetKey,
              child: Container(
                color: Colors.white,
                child: Column(
                  children: [
                    Text(title??'',style: TextStyle(fontSize: 25,fontWeight: FontWeight.bold,),),
                    Column(
                        children: configList.map((config) => _textRow(config)).toList()
                    ),
                    QrImage(
                      data: qrCode,
                      size: 220,
                    ),
                  ],
                )
              )
            )
          ],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 600,
      height: 600,
      child: result,
    );
  }
}

class BluetoothDeviceDialog extends StatefulWidget {
  String? data;
  Uint8List? image;

  BluetoothDeviceDialog({required this.data, this.image, key})
      : super(key: key);
  @override
  _BluetoothDeviceDialogState createState() => _BluetoothDeviceDialogState();
}

class _BluetoothDeviceDialogState extends State<BluetoothDeviceDialog> {
  BluetoothPrint bluetoothPrint = BluetoothPrint.instance;

  bool _connected = false;
  BluetoothDevice _device = BluetoothDevice();
  String tips = '没有设备连接';

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance!.addPostFrameCallback((_) => initBluetooth());
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initBluetooth() async {
    bluetoothPrint.startScan(timeout: Duration(seconds: 4));

    bool? isConnected = await bluetoothPrint.isConnected;

    tips = isConnected! ? '连接成功':'没有设备连接';
    bluetoothPrint.state.listen((state) {
      print('cur device status: $state');

      switch (state) {
        case BluetoothPrint.CONNECTED:
        //延时500毫秒执行
          Future.delayed(const Duration(milliseconds: 500), () {
            //延时执行的代码
            setState(() {
              _connected = true;
              tips = '连接成功';
            });
          });
          break;
        case BluetoothPrint.DISCONNECTED:
          setState(() {
            _connected = false;
            tips = '断开成功';
          });
          break;
        default:
          break;
      }
    });

    if (!mounted) return;

    if (isConnected) {
      setState(() {
        _connected = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("选择设备"),
        ),
        body: RefreshIndicator(
          onRefresh: () =>
              bluetoothPrint.startScan(timeout: Duration(seconds: 4)),
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Padding(
                      padding:
                      EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                      child: Text(tips),
                    ),
                  ],
                ),
                Divider(),
                StreamBuilder<List<BluetoothDevice>>(
                  stream: bluetoothPrint.scanResults,
                  initialData: [],
                  builder: (c, snapshot) => Column(
                    children: snapshot.data!
                        .map((d) => ListTile(
                      title: Text(d.name ?? ''),
                      subtitle: Text(d.address!),
                      onTap: () async {
                        setState(() {
                          _device = d;
                        });
                      },
                      trailing: _device != null &&
                          _device.address == d.address
                          ? Icon(
                        Icons.check,
                        color: Colors.green,
                      )
                          : null,
                    ))
                        .toList(),
                  ),
                ),
                Divider(),
                Container(
                  padding: EdgeInsets.fromLTRB(20, 5, 20, 10),
                  child: Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          OutlinedButton(
                            child: Text('连接'),
                            onPressed: _connected
                                ? null
                                : () async {
                              if (_device != null &&
                                  _device.address != null) {
                                await bluetoothPrint.connect(_device);
                              } else {
                                setState(() {
                                  tips = 'please select device';
                                });
                                print('please select device');
                              }
                            },
                          ),
                          SizedBox(width: 10.0),
                          OutlinedButton(
                            child: Text('断开'),
                            onPressed: _connected
                                ? () async {
                              await bluetoothPrint.disconnect();
                            }
                                : null,
                          ),
                        ],
                      ),
                      OutlinedButton(
                        child: Text('打印'),
                        onPressed: _connected
                            ? () async {
                          Map<String, dynamic> config = Map();
                          config['width'] = 80; // 标签宽度，单位mm
                          config['height'] = 250; // 标签高度，单位mm
                          config['gap'] = 2; // 标签间隔，单位mm
                          List<LineText> Lienlist = [];
                          Lienlist.add(LineText(
                              type: LineText.TYPE_IMAGE,
                              x: 10,
                              y: 10,
                              content: widget.data,
                              align: LineText.ALIGN_CENTER));
                          await bluetoothPrint.printLabel(
                              config, Lienlist);
                        }
                            : null,
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
        floatingActionButton: StreamBuilder<bool>(
          stream: bluetoothPrint.isScanning,
          initialData: false,
          builder: (c, snapshot) {
            if (snapshot.data!) {
              return FloatingActionButton(
                child: Icon(Icons.stop),
                onPressed: () => bluetoothPrint.stopScan(),
                backgroundColor: Colors.red,
              );
            } else {
              return FloatingActionButton(
                  child: Icon(Icons.search),
                  onPressed: () =>
                      bluetoothPrint.startScan(timeout: Duration(seconds: 4)));
            }
          },
        ),
      );
  }
}
